import Node from './Node'
import Text from './Text'
import Img from './Img'

class View extends Node {
	constructor(name) {
		super(name)
		let text = new Text('')
		text.parent = this
		Object.defineProperties(this, {
			tag: {
				value: 'view'
			},
			text: {
				set(val) {
					if (text.data != val) {
						text.data = val
					}
				},
				get() {
					return text.data
				}
			},
			textNode: {
				value: text
			}
		})
	}
	create(options) {
		let el = null
		switch (options.tag) {
			case 'view':
				el = new View(options.name)
				break;
			case 'img':
				el = new Img(options.name)
				break
		}
		if (el) {
			el.parent = this
			el.compute()
			el.setStyle(options.style)
			this.children.push(el)
		}
		return el
	}
	render(ctx) {
		if (!ctx) return
		let props = this.props,
			points = this.points
		ctx.save()
		ctx.translate(this.center[0], this.center[1])
		//opacity
		ctx.globalAlpha = props.opacity
		// ctx.setGlobalAlpha(props.opacity)
		//rotate
		ctx.rotate(props.rotate)
		//scale
		// console.log(props.scale+'')
		ctx.scale(props.scale[0], props.scale[1])
		//阴影
		if (props.shadow.length === 4) {
			ctx.shadowColor = props.shadow[0]
			ctx.shadowOffsetX = props.shadow[1]
			ctx.shadowOffsetY = props.shadow[2]
			ctx.shadowBlur = props.shadow[3]
		}
		ctx.beginPath()
		ctx.moveTo(points[0][0], points[0][1])
		ctx.arcTo(points[1][0], points[1][1], points[2][0], points[2][1], props.radius[0])
		ctx.arcTo(points[3][0], points[3][1], points[4][0], points[4][1], props.radius[1])
		ctx.arcTo(points[5][0], points[5][1], points[6][0], points[6][1], props.radius[2])
		ctx.arcTo(points[7][0], points[7][1], points[0][0], points[0][1], props.radius[3])
		ctx.closePath()
		//填充色
		if (props.background) {
			ctx.fillStyle = props.background
			ctx.fill()
		}
		//边框
		if (props.border[0] > 0 && props.border[1]) {
			ctx.lineWidth = props.border[0]
			ctx.strokeStyle = props.border[1]
			ctx.stroke()
		}
		ctx.restore()
		//子级继承
		ctx.save()
		ctx.translate(this.center[0], this.center[1])
		//opacity
		ctx.globalAlpha = props.opacity
		//rotate
		ctx.rotate(props.rotate)
		//scale
		ctx.scale(props.scale[0], props.scale[1])
		//overflow
		if (this.props.overflow === 'hidden') {
			ctx.globalCompositeOperation = 'source-atop'
		}
		// console.log(this.name, props.scale)
		//文字
		if (this.textNode.data) this.textNode.render(ctx)
		//children
		for (let i = 0, len = this.children.length, child = null; i < len; i++) {
			child = this.children[i]
			if (child.render) child.render(ctx)
		}
		ctx.restore()
	}
}

export default View